#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <stdint.h>
#include "DefultParameter.h"
#include "bsp_flash.h"
#include "bsp_uart.h"
#include "msg_package.h"

char factoryStep = 0;

unsigned short crc16(void *p_data, int size)
{
    unsigned short crc = 0xe1b5;
    char *data = p_data;

    for (int i = 0; i < size; i++)
    {
        crc = (unsigned char)(crc >> 8) | (crc << 8);
        crc ^= (unsigned char)data[i];
        crc ^= (unsigned char)(crc & 0xFF) >> 4;
        crc ^= (crc << 8) << 4;
        crc ^= ((crc & 0xFF) << 4) << 1;
    }
    return crc;
}

void device_factory_test(void)
{
    if (uart1_msg.state == MSG_RECV_COMP)
    {
        if (strstr(uart1_msg.buff, "EBYTE_FACTORY"))
        {
            if (bsp_flash_page_erase(DEVICE_SN_FLASH_ADDR))
            {
                uart_send_string("\r\nDEVICE_ERROR\r\n");
            }
            else
            {
                uart_send_string("\r\nDEVICE_BEGIN\r\n");
                factoryStep = 1;
            }
        }
        else if (strstr(uart1_msg.buff, "AT+SN=") && factoryStep == 1)
        {
            device_sn_t sn = {0};
            if (1 == sscanf((char *)uart1_msg.buff, "AT+SN=%s\r\n", sn.sn_code))
            {
                sn.crc = crc16((void *)sn.sn_code, DEVICE_SN_MAX_SIZE);
                sn.factory_sucess_mark = FACTORY_MARK;
                if (bsp_flash_page_write(DEVICE_SN_FLASH_ADDR, (uint8_t *)&sn, sizeof(device_sn_t)))
                {
                    uart_send_string("\r\nDEVICE_ERR_SN\r\n");
                }
                else
                {
                    char temp[50] = {0};
                    memcpy(temp, "\r\nDEVICE_SN", sizeof("\r\nDEVICE_SN") - 1);
                    int len = get_devinfo_SN(temp, sizeof("\r\nDEVICE_SN") - 1);
                    uart_send_string(temp);
                }
            }
            else
            {
                uart_send_string("\r\nDEVICE_ERR_CMD\r\n");
            }
        }
        else
        {
            factoryStep = 0;
        }
    }
}
